<?php
/**
 *  Connection management class
 *
 */
class Yz_SQL_Adapter
    extends Yz_Class
{

    /** The currently open connections
     *  @var array
     */
    protected $connections = array();

    protected static $instance;

    /** selectConnection() : select (and open if not opened) a connection to a SQL server
     *  @param string name
     *  @return <Yz_SQL_Adapter_Interface&>
     *  @throw Yz_SQL_Exception, and the adapter's exceptions on failing to connect
     */
    public static function selectConnection( $name=null )
    {
        if (null === $name) {
            $name = 'default';
        } else {
            $name = Yz_String::testNotEmpty($name);
        }
        $mgr = self::getInstance();
        return $mgr($name);
    }

    /**
    * static getInstance():
    *
    */
    protected static function getInstance()
    {
        debug();

        if ( null === self::$instance ) {
            self::$instance = new self;
        }

        return self::$instance;
    } // getInstance()


    protected function __construct()
    {
        return;
    }

    /** __invoke() : couldn't find a more suitable name
     *
     */
    protected function __invoke( $name )
    {
        if (! isset($this->connections[$name])) {
            $this->connections[$name] = $this->connect($name);
        }
        return $this->connections[$name];
    }



    protected function connect( $name )
    {
        $cfg = Yz::getConfig()->fetchString('sql.connection.' . $name);
        if (! $cfg) {
            throw new Yz_SQL_Exception("Failed to open connection '$name'");
        }

        $conn = new Yz_SQL_Adapter_Mysqli($cfg);

        return $conn;
    }

}
